<template>
    <div class="tabs-container">
        <div class="tabs-header">
            <div v-for="(tab, i) in tabs" :key="i" class="tab-item" :class="{ active: activeIndex === i }"
                :style="activeStyle(i)" @click="handleTabClick(tab, i)">
                <slot name="title" :tab="tab">
                    {{ tab.label }} {{ tab.quantity }}
                </slot>
            </div>
        </div>
        <div class="tabs-content">
            <slot></slot>
        </div>
    </div>
</template>

<script setup lang="ts">

const props = defineProps({
    //默认激活的索引
    modelValue: {
        type: Number,
        default: 0
    },
    //激活颜色
    activeColor: {
        type: String,
        default: "#409eff"
    },
    //是否使用路由
    router: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(["update:modelValue", "tab-change"])

const activeIndex = ref(props.modelValue)


const tabs = ref<TabItem[]>([])

//激活状态样式
const activeStyle = (index: number) => ({
    color: activeIndex.value === index ? props.activeColor : ""
})

function handleTabClick(tab: any,index: number) {
    if (props.router && tab.path) {
        window.location.hash = tab.path
    }
    activeIndex.value = index
    emit("update:modelValue", tab)
    emit("tab-change", tab)
}
//注册子组件
const registerTab = (tab:any) => {
    const index = tabs.value.length;
    tabs.value.push({ ...tab });
    return index;
}

const unregisterTab = (index: number,quantity:number) => {
    if(quantity && tabs.value.length){
        tabs.value[index].quantity = quantity
    }
}

//向子组件提供上下文
provide('tabsContext', {
    activeIndex,
    registerTab,
    unregisterTab
})

//监听modelValue变化
watch(() => props.modelValue, (val) => {
    activeIndex.value = val
})
</script>

<style lang="scss" scoped>
.tabs-container {
    width: 100%;
}

.tabs-header {
    position: relative;
    display: flex;

}

.tab-item {
    font-size: 14px;
    line-height: 40px;
    height: 40px;
    color: #333;
    margin-right: 30px;
    transition: all 0.3s;
    font-weight: 700;
    position: relative;
    cursor: pointer;

    &.active {
        background: linear-gradient(to right, #407fff, #29aafe);
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
        font-weight: bold;
        transition: all 0.3s;

        &::after {
            content: '';
            width: 100%;
            transition: all 0.3s;
        }
    }

    &::after {
        content: '';
        width: 0%;
        height: 3px;
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translateX(-50%);
        background: linear-gradient(to right, #407fff, #29aafe);
        transition: all 0.3s;
    }
}
</style>